package gitapp.oschina.net.my_osc.common;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

import gitapp.oschina.net.my_osc.AppManager;

/**
 * @author Tristan-Hou
 */
public class DoubleClickExitHelper {
    private final Activity mActivity;

    private boolean isOnKeyBacking;
    private Handler mHandler;
    private Toast mBackToast;

    public DoubleClickExitHelper(Activity activity){
        mActivity = activity;
        mHandler = new Handler(Looper.getMainLooper());
    }

    public boolean onKeyDown(int keyCode, KeyEvent event){
        if (keyCode != KeyEvent.KEYCODE_BACK){
            return false;
        }
        if (isOnKeyBacking){
            mHandler.removeCallbacksAndMessages(null);
            AppManager.getAppManager().AppExit();
            return true;
        }else {
            isOnKeyBacking = true;
            if (mBackToast == null) {
                mBackToast = Toast.makeText(mActivity,
                        "再按一次退出", Toast.LENGTH_LONG);
                mBackToast.show();
            }
            mHandler.postDelayed(onBacktimeRunnable, 2000);
            return true;
        }
    }

    private Runnable onBacktimeRunnable = new Runnable() {
        @Override
        public void run() {
            isOnKeyBacking = false;
            if (mBackToast != null)
                mBackToast.cancel();
        }
    };
}
